<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="填报对象" prop="reportObj">
        <el-select v-model="queryParams.reportObj" placeholder="填报对象" @change="getList" clearable>
          <el-option
            v-for="dict in dict.type.business_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="填报周期" prop="reportCycle">
        <el-select v-model="queryParams.reportCycle" placeholder="填报周期" @change="getList" clearable>
          <el-option
            v-for="dict in dict.type.filling_cycle"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" v-show="isFoldQuery">
        <el-date-picker
          v-model="createDateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
<!--      <el-form-item label="截止日期" prop="deadline">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.deadline"-->
<!--          type="date"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择截止日期">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          plain
          :icon="isFoldQuery ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"
          size="mini"
          @click="foldQuery"
        >
          {{ isFoldQuery ? '折叠' : '展开' }}
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['reportTask:reportTaskCenter:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit-outline"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['reportTask:reportTaskCenter:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['reportTask:reportTaskCenter:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['reportTask:reportTaskCenter:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="reportTaskCenterList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="主键id" align="center" prop="id" v-if="false" />
      <el-table-column label="任务链接" align="center" prop="taskUrl" width="400" >
        <template #default="scope">
          <div>
            {{ scope.row.id }}
            <el-button
            link
            type="text"
            icon="el-icon-copy-document"
            @click="copyData(scope.row.taskUrl+scope.row.id)"
          ></el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="任务名称" align="center" prop="taskName" width="250"/>

      <el-table-column label="任务状态" align="center" prop="taskStatus" width="180">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_status" :value="scope.row.taskStatus"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="生成时间" align="center" prop="genDate" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.genDate, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="开始日期" align="center" prop="sendDate" width="180">
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.sendDate, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="截止日期" align="center" prop="deadline" width="180">
        <!--        <template slot-scope="scope">-->
        <!--          <span>{{ parseTime(scope.row.deadline, '{y}-{m}-{d}') }}</span>-->
        <!--        </template>-->
      </el-table-column>

      <el-table-column label="填报对象" align="center" prop="reportObj" width="180" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.business_type" :value="scope.row.reportObj"/>
        </template>
      </el-table-column>
      <el-table-column label="填报周期" align="center" prop="reportCycle" width="180">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.filling_cycle" :value="scope.row.reportCycle"/>
        </template>
      </el-table-column>
      <el-table-column label="发送数量" align="center" prop="sendNum" width="180"/>
      <el-table-column label="填报说明" align="left" prop="remark" width="250" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="400">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="previewTemplates(scope.row.id)"
            v-hasPermi="['reportTask:reportTaskCenter:edit']"
          >查看填报模板</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-document"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['reportTask:reportTaskCenter:edit']"-->
<!--          >查看填报记录</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit-outline"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['reportTask:reportTaskCenter:edit']"
          >变更截止时间</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['reportTask:reportTaskCenter:remove']"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改填报任务中心对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="生成时间" prop="genDate" >
          <el-date-picker clearable disabled
            v-model="form.genDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择生成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="截止日期" prop="deadline">
          <el-date-picker clearable disabled
            v-model="form.deadlineOld"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择截止日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="截止日期" prop="deadline">
          <el-date-picker clearable
                          v-model="form.deadline"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择截止日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReportTaskCenter, getReportTaskCenter, delReportTaskCenter, addReportTaskCenter, updateReportTaskCenter } from "@/api/reportTask/reportTaskCenter";

export default {
  name: "ReportTaskCenter",
  dicts: ['task_status', 'business_type', 'filling_cycle'],
  data() {
    return {
      isFoldQuery:false,
      // 日期范围
      createDateRange: [],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 填报任务中心表格数据
      reportTaskCenterList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskUrl: undefined,
        taskName: undefined,
        genDate: undefined,
        deadlineOld: undefined,
        deadline: undefined,
        reportObj: undefined,
        reportCycle: undefined,
        taskStatus: undefined,
        sendNum: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "主键id不能为空", trigger: "blur" }
        ],
        taskUrl: [
          { required: true, message: "任务链接不能为空", trigger: "blur" }
        ],
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        genDate: [
          { required: true, message: "生成时间不能为空", trigger: "blur" }
        ],
        deadline: [
          { required: true, message: "截止日期不能为空", trigger: "blur" }
        ],
        reportObj: [
          { required: true, message: "填报对象不能为空", trigger: "blur" }
        ],
        reportCycle: [
          { required: true, message: "填报周期不能为空", trigger: "blur" }
        ],
        taskStatus: [
          { required: true, message: "任务状态不能为空", trigger: "change" }
        ],
        sendNum: [
          { required: true, message: "发送数量不能为空", trigger: "blur" }
        ],
        remark: [
          { required: true, message: "备注不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询填报任务中心列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.createDateRange && '' != this.createDateRange) {
        this.queryParams.params['beginCreateTime'] = this.createDateRange[0]
        this.queryParams.params['endCreateTime'] = this.createDateRange[1]
      }
      listReportTaskCenter(this.queryParams).then(response => {
        this.reportTaskCenterList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        taskUrl: undefined,
        taskName: undefined,
        genDate: undefined,
        deadlineOld: undefined,
        deadline: undefined,
        reportObj: undefined,
        reportCycle: undefined,
        taskStatus: undefined,
        sendNum: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      console.log("点击重置按钮")
      this.createDateRange = []
      this.resetForm("queryForm");
      this.handleQuery();
    },
    foldQuery() {
      this.isFoldQuery = !this.isFoldQuery;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加填报任务中心";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getReportTaskCenter(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.form.deadlineOld = response.data.deadline;
        this.open = true;
        this.title = "变更截止时间";
      });
    },
    previewTemplates(id) {
      const params = new URLSearchParams({
        taskCenterId: id,
        isPreview: true
      }).toString()
      window.open(`/report/previewFill/reportFill?${params}`, '_blank')
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateReportTaskCenter(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addReportTaskCenter(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除填报任务中心编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delReportTaskCenter(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('reportTask/reportTaskCenter/export', {
        ...this.queryParams
      }, `reportTaskCenter_${new Date().getTime()}.xlsx`)
    },  /**
     * 复制文本到剪贴板
     * @param {String} text 要复制的内容
     */
    copyData(text) {
      if (!text) {
        this.$message.warning("内容为空，无法复制");
        return;
      }
      // 使用浏览器原生Clipboard API
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(text).then(() => {
          this.$message.success("复制成功");
        }).catch(() => {
          this.$message.error("复制失败，请手动复制");
        });
      } else {
        // fallback：老式方法
        const textarea = document.createElement("textarea");
        textarea.value = text;
        textarea.style.position = "fixed";  // 避免滚动条
        textarea.style.opacity = "0";
        document.body.appendChild(textarea);
        textarea.focus();
        textarea.select();
        try {
          const successful = document.execCommand('copy');
          if (successful) {
            this.$message.success("复制成功");
          } else {
            this.$message.error("复制失败，请手动复制");
          }
        } catch (err) {
          this.$message.error("复制失败，请手动复制");
        }
        document.body.removeChild(textarea);
      }
    }
  }
};
</script>
